//
//  PersonalInforationViewController.m
//  EcmDoctor
//
//  Created by Mac on 16/2/16.
//  Copyright © 2016年 张进. All rights reserved.
//

#import "PersonalInforationViewController.h"
#import "MainTabBarController.h"
#import <SSKeychain/SSKeychain.h>
#import "AppUtils.h"
#import "DoctorIcon.h"
#import "UIImageView+AFNetworking.h"
#import "DoctorIfo.h"
#import "MedicineListm.h"
#import "RefreshToken.h"
@interface PersonalInforationViewController ()
{
    __weak IBOutlet UIButton *_enterMainViewBtn;
    __weak IBOutlet NSLayoutConstraint *_headImageViewHeight;
    
    __weak IBOutlet UILabel *_userLevel;
    __weak IBOutlet UILabel *_userName;
    __weak IBOutlet NSLayoutConstraint *personImageViewWidth;
    __weak IBOutlet NSLayoutConstraint *personImageViewHeight;
    __weak IBOutlet UIImageView *_personImageView;
    __weak IBOutlet UITextView *_userInformation;
    
}
@end

@implementation PersonalInforationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationItem setHidesBackButton:YES];
    
    self.navigationItem.titleView=[AppUtils generateNavigationItemTitleViewWithTitle:@"E中医"];
    
    _enterMainViewBtn.titleLabel.font = [AppUtils getCustomFontWithSize:24];
    CGFloat wh;
    if(kScreenHeight<667)
    {
        
        wh=70;
        _headImageViewHeight.constant=kScreenHeight/3;
    }
    else if(kScreenHeight==667)
    {
       wh=80;
        _headImageViewHeight.constant=kScreenHeight/4+30;
        
    }
    else
    {
        wh=90;
       _headImageViewHeight.constant=kScreenHeight/4+30;
    }
   
    personImageViewHeight.constant=wh;
    personImageViewWidth.constant=wh;

   
    
    _personImageView.layer.borderColor=[UIColor colorWithRed:228/255.0 green:211/255.0 blue:185/255.0 alpha:1].CGColor;
    _personImageView.layer.borderWidth=2;
    _personImageView.backgroundColor=[UIColor clearColor];
    _personImageView.layer.cornerRadius=personImageViewWidth.constant/2;
    

}

-(void)downloadmedicinelist
{
   
    NSString * DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSData *data=[NSData dataWithContentsOfFile:[DocumentsPath stringByAppendingString:@"/cureinfom"]];
     NSArray *clientDrugInfoAry = [NSKeyedUnarchiver unarchiveObjectWithData:data];
   

    [MedicineListm getDrugInfoYBwithclientDrugInfo:clientDrugInfoAry success:^(NSArray *medicinelistAry) {
        
        } failure:^(NSError *error) {
            
        NSLog(@"----------%@",error.localizedDescription);
    }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 6.0) {
        
        //需要注意的是self.isViewLoaded是必不可少的，其他方式访问视图会导致它加载 ，在WWDC视频也忽视这一点。
        
        if (self.isViewLoaded && !self.view.window)// 是否是正在使用的视图
        {
            // Add code to preserve data stored in the views that might be
            // needed later.
            
            // Add code to clean up other strong references to the view in
            // the view hierarchy.
            self.view = nil;// 目的是再次进入时能够重新加载调用viewDidLoad函数。
        }
        
    }
    // Dispose of any resources that can be recreated.
}
- (IBAction)enterTheMainView:(id)sender {
    
    CATransition *animation = [CATransition animation];
    [animation setDuration:0.4];
    [animation setType: kCATransitionPush];
    
    [animation setSubtype: kCATransitionFromRight];
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
    
    [self.navigationController.view.layer addAnimation:animation forKey:nil];
    
    [self.navigationController popViewControllerAnimated:NO];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    if ([segue.identifier isEqualToString:@"enterTheMainView"]) {
        
        
    }
}
-(void)changeToNavRootController:(id)sender{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)setValue
{
    NSUserDefaults *doctorUser=[NSUserDefaults standardUserDefaults];
    NSString *maxSidStr;
    if([doctorUser objectForKey:@"maxSid"])
        maxSidStr=[doctorUser objectForKey:@"maxSid"];
    else  maxSidStr=@"0";
    
    [MedicineListm judgeIsUpdateDrugInfoYBWithmaxSid:maxSidStr success:^(NetWorkBaseResponse *responseObject) {
        NSNumber *num=responseObject.data;
        NSString * DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"/Documents"];
        NSData *data=[NSData dataWithContentsOfFile:[DocumentsPath stringByAppendingString:@"/clientDrugInfo"]];
        NSArray *arr2 = [NSKeyedUnarchiver unarchiveObjectWithData:data];
       if(arr2.count)
       {
        if(num.intValue==1)
        [self downloadmedicinelist];
       }
        else
            [self downloadmedicinelist];
            
    } failure:^(NSError *error) {
        NSLog(@"%@",error.localizedDescription);
    }];

    if(self.myInfo==1)
    {
        UIImage *tableIcon = [UIImage imageNamed:@"btn_back"];
        self.navigationItem.leftBarButtonItem =[[UIBarButtonItem alloc] initWithImage:tableIcon style:UIBarButtonItemStylePlain target:self action:@selector(changeToNavRootController:)];
        self.navigationItem.leftBarButtonItem.tintColor = [UIColor colorWithPatternImage:tableIcon];
        _enterMainViewBtn.alpha=0;
    }
   
    if(![[doctorUser objectForKey:APP_KEY ] isEqualToString:@"dengluOk"])
    {
        [self performSegueWithIdentifier:@"segueLogin" sender:self];
        
    }
    else
    {
        NSString *phone= [SSKeychain passwordForService:APP_SERVICE_NAME account:APP_PHONENUM_KEY];
        NSString *passWard= [doctorUser objectForKey:APP_USERPASSWORD_KEY];
        NSString *docId= [SSKeychain passwordForService:APP_SERVICE_NAME account:APP_DOCTORINFOID_KEY];
        [DoctorIfo loginWithUsername:phone Password:passWard success:^(DoctorIfo *doctor) {
            
            if([doctorUser objectForKey:APP_DOCTORICON_KEY])
            {
                [self setDoctorIconWith:[doctorUser objectForKey:APP_DOCTORICON_KEY]];
            }
            else
            {
                
                [DoctorIcon requetDoctorInfoWith:docId success:^(DoctorIcon *doctorIcon) {
                    
                    [doctorUser setObject:doctorIcon.myHead forKey:APP_DOCTORICON_KEY];
                    [doctorUser synchronize];
                    [self setDoctorIconWith:doctorIcon.myHead];
                } failure:^(NSError *error) {
                    NSLog(@"%@",error.localizedDescription);
                }];
            }
            
            if(self.myInfo!=1)
                [DoctorIfo getDoctorWorkStateWithDoctorinfId:docId success:^(DoctorIfo *doctor) {
                    NSLog(@"-------%@",doctor);
                } failure:^(NSError *error) {
                    NSLog(@"%@",error.localizedDescription);
                }];
            
            _userName.text=[NSString stringWithFormat:@"【%@】",[doctorUser objectForKey:APP_DOCTORNAME_KEY] ];
            _userLevel.text=[doctorUser objectForKey:APP_JOBPOSITION_KEY];
            
            _userInformation.text=[doctorUser objectForKey:APP_SPECIALDES_KEY];
        
         } failure:^(NSError *error) {
        NSLog(@"%@",error.localizedDescription);
        
    }];
//        [RefreshToken changeTokenfailure:^(NSError *error) {
//            NSLog(@"%@",error.localizedDescription);
//        }];

        
    }

}
-(void)setDoctorIconWith:(NSString *)iconStr
{
    NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:@"http://ecm-user.oss-cn-beijing.aliyuncs.com/image/%@",iconStr]];
    [ _personImageView setImageWithURL:url placeholderImage:[UIImage imageNamed:@"icon"]];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    [self setValue];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
